<template>
  <div class="editor-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="所属模块" prop="module">
        <el-select v-model="form.module">
          <el-option label="隐私协议" value="2"></el-option>
          <el-option label="用户协议" value="6"></el-option>
        </el-select>
      </el-form-item>
      <!-- 图片上传组件辅助-->
      <el-upload
        class="avatar-uploader"
        :action="serverUrl"
        name="img"
        :show-file-list="false"
        :http-request="uploadImage"
      ></el-upload>
      <el-form-item label="内容" prop="content" class="vab-quill-content">
        <el-row v-loading="quillUpdateImg">
          <vab-quill
            ref="myQuillEditor"
            v-model="form.content"
            :min-height="400"
            :options="options"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)"
          ></vab-quill>
        </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSee">预览效果</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="预览效果" :visible.sync="dialogTableVisible">
      <div style="min-height: 60vh">
        <div class="news-content" v-html="form.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import vabQuill from '@/plugins/vabQuill'
  import _constant from '../../config/net.config'
  import { modUserAgreement, getUserAgreement, setInfo } from '@/api/info'
  import { upload } from '@/api/upload'

  // 工具栏配置
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    ['blockquote', 'code-block'],

    [{ header: 1 }, { header: 2 }], // custom button values
    [{ list: 'ordered' }, { list: 'bullet' }],
    [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
    [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
    [{ direction: 'rtl' }], // text direction

    [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
    [{ header: [1, 2, 3, 4, 5, 6, false] }],

    [{ color: [] }, { background: [] }], // dropdown with defaults from theme
    [{ font: [] }],
    [{ align: [] }],
    ['image'],
    ['clean'], // remove formatting button
  ]

  export default {
    name: 'Editor',
    components: { vabQuill },
    data() {
      return {
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
        serverUrl: _constant.baseURL + '/file/upload', // 这里写你要上传的图片服务器地址
        options: {
          theme: 'snow',
          bounds: document.body,
          debug: 'warn',
          modules: {
            toolbar: {
              container: toolbarOptions, // 工具栏
              handlers: {
                image: function (value) {
                  if (value) {
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false)
                  }
                },
              },
            },
          },
        },
        imageUrl: '',
        image: '',
        borderColor: '#dcdfe6',
        dialogTableVisible: false,
        imageUrlfileList: [],
        form: {
          module: '',
          content: '',
          imageUrl: null,
        },
        rules: {
          module: [
            {
              required: true,
              message: '请选择模块',
              trigger: 'change',
            },
          ],
          content: [
            {
              required: true,
              message: '请输入内容',
              trigger: 'blur',
            },
          ],
        },
      }
    },
    watch: {
      'form.module': {
        handler(newName, oldName) {
          if (newName == '') {
            return
          }
          this.getContent(newName)
        },
        immediate: true,
        deep: true,
      },
    },
    methods: {
      async getContent(id) {
        let agreementId = ''
        if (id == 2) {
          agreementId =
            'fecmzvefuiezpvhdfwsocbvpcdzroruxnbaynnczphyagouiayrwtbzhuhbuhuem'
        } else {
          agreementId =
            'zknboyaitksthudndlvrxrsivbeddfkiggvftvhvizauasdzfbwxykgdldbbutaq'
        }
        const { data } = await getUserAgreement(agreementId)
        if (data.status == 0) {
          this.form.content = data.body.text ? data.body.text : ''
        } else {
          this.$baseMessage(data.message, 'error')
        }
      },
      // // 上传组件获得的图片地址反渲染近富文本中
      // handleSuccess(res) {
      //   // 获取富文本组件实例
      //   let quill = this.$refs.QuillEditor.Quill
      //   // 如果上传成功
      //   if (res) {
      //     // 获取光标所在位置
      //     let length = quill.getSelection().index
      //     // 插入图片，res为服务器返回的图片链接地址
      //     quill.insertEmbed(length, 'image', res)
      //     // 调整光标到最后
      //     quill.setSelection(length + 1)
      //   } else {
      //     // 提示信息，需引入Message
      //     Message.error('图片插入失败')
      //   }
      // },
      // handleAvatarSuccess(res, file) {
      //   this.image = res.url
      //   this.handleSuccess(res.url)
      //   this.imageUrl = URL.createObjectURL(file.raw)
      // },
      // beforeAvatarUpload(file) {
      //   const isJPG = file.type === 'image/jpeg'
      //   const isLt2M = file.size / 1024 / 1024 < 2

      //   if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 JPG 格式!')
      //   }
      //   if (!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 2MB!')
      //   }
      //   return isJPG && isLt2M
      // },
      // imageUrlBeforeUpload(file) {
      //   let isRightSize = file.size / 1024 / 1024 < 2
      //   if (!isRightSize) {
      //     this.$message.error('文件大小超过 2MB')
      //   }
      //   return isRightSize
      // },
      async uploadImage(param) {
        const formData = new FormData()
        // formData.fileType = 1
        formData.append('fileType', 1)
        formData.append('file', param.file)
        console.log(formData)
        this.quillUpdateImg = true
        const { data } = await upload(formData)
        // let base = 'https://app.aixinfang.vip'
        let base = _constant.baseURL
        let imageUrl = base + '/file/download?fileId=' + data.body.fileId

        if (data.status == 0) {
          console.log(this.$refs.myQuillEditor)
          let quill = this.$refs.myQuillEditor.Quill
          console.log(quill)
          // 如果上传成功
          // 获取光标所在位置
          let length = quill.getSelection().index
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, 'image', imageUrl)
          // 调整光标到最后
          quill.setSelection(length + 1)

          // loading动画消失
          this.quillUpdateImg = false
        } else {
          this.quillUpdateImg = false
          this.$message.error('图片插入失败')
        }
      },
      handleSee() {
        this.$refs['form'].validate((valid) => {
          this.$refs.form.validateField('content', (errorMsg) => {})
          if (valid) {
            this.dialogTableVisible = true
          } else {
            return false
          }
        })
      },
      handleSave() {
        this.$refs['form'].validate((valid) => {
          this.$refs.form.validateField('content', (errorMsg) => {
            const condition = this.form.module
            const formatData = {}
            formatData.baseId = '1'
            let pushData = {}
            if (condition == 2) {
              pushData.agreementId = _constant.privacyTreatyId
            }
            if (condition == 6) {
              pushData.agreementId = _constant.userTreatyId
            }
            pushData.text = this.form.content
            modUserAgreement(pushData).then((res) => {
              this.$notify({
                title: '成功',
                message: '提交成功！',
                type: 'success',
                duration: 2000,
              })
            })
            this.borderColor = '#dcdfe6'
            if (errorMsg) {
              this.borderColor = '#F56C6C'
            }
          })
        })
      },
    },
  }
</script>
<style lang="scss" scoped>
  .editor-container {
    .news {
      &-title {
        text-align: center;
      }

      &-content {
        ::v-deep {
          p {
            line-height: 30px;

            img {
              display: block;
              margin-right: auto;
              margin-left: auto;
            }
          }
        }
      }
    }

    .vab-quill-content {
      ::v-deep {
        .el-form-item__content {
          line-height: normal;
        }
      }
    }
  }
  .avatar-uploader {
    display: none;
  }
</style>
